<template>
  <!-- 搜索历史数据保存在本地，
	 当用户对该数据进行了搜索之后，那么该数据就算是搜索历史的数据了
	  -->
  <view class="search-history-container">
    <!-- title -->
    <view class="search-history-title-box">
      <view class="search-history-title">搜索历史</view>
      <view v-if="!isShowClear">
        <uni-icons type="trash" @click="isShowClear = true" />
      </view>
      <view v-else>
        <text class="txt" @click="onClearAll">全部删除</text>
        <text class="txt" @click="isShowClear = false">完成</text>
      </view>
    </view>
    <!-- 内容 -->
    <view class="search-history-box">
      <block v-for="(item, index) in searchData" :key="index">
        <view
          class="search-history-item"
          @click="onHistoryItemClick(item, index)"
        >
          <text class="history-txt line-clamp">{{ item }}</text>
          <uni-icons v-show="isShowClear" type="clear" />
        </view>
      </block>
    </view>
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  name: "search-history",
  data() {
    return {
      isShowClear: false,
    };
  },
  methods: {
    // 利用mapMutations函数 可以直接把vuex中的mutation合在一起
    ...mapMutations("search", ["removeSearchData", "removeAllSearchData"]),
    /**
     * 全部删除
     */
    onClearAll() {
      uni.showModal({
        title: "提示",
        content: "删除搜索历史数据？",
        showCancel: true,
        success: ({ confirm, cancel }) => {
          if (confirm) {
            this.removeAllSearchData();
            this.isShowClear = false;
          }
        },
      });
    },
    /**
     * item的点击事件
     */
    onHistoryItemClick(item, index) {
      if (this.isShowClear) {
        // 1.当前处于 删除状态下，点击删除item
        this.removeSearchData(index);
      } else {
        // 2.当前不处于删除状态下，进行搜索处理
        console.log(item);
        this.$emit("onSearch", item);
      }
    },
  },
  computed: {
    // 在computed中，通过mapState函数 注册state中的数据，导入之后的数据可以直接使用，像data中的数据一样
    ...mapState("search", ["searchData"]),
  },
};
</script>

<style lang="scss" scoped>
.search-history-container {
  padding: 12px 15px;
  .search-history-title-box {
    display: flex;
    justify-content: space-between;
    .search-history-title {
      font-size: 12px;
      color: #333;
      padding: 4px 5px;
    }
    .txt {
      color: gray;
      font-size: 12px;
      padding: 12px 15px;
    }
  }
  .search-history-box {
    margin-top: 15px;
    .search-history-item {
      width: 50%;
      box-sizing: border-box;
      display: inline-block;
      padding: 8px 10px;
      position: relative;
      .history-txt {
        width: 85%;
        display: inline-block;
        color: #333;
        font-size: 14px;
      }
    }
    .search-history-item:nth-child(odd)::before {
      content: "";
      border-left: 1px solid #999;
      display: inline-block;
      height: 10px;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 0;
    }
  }
}
</style>
